package com.dating.base.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.dating.base.bean.Permission;
import com.dating.base.bean.Role;
import com.dating.base.bean.User.Type;
import com.dating.core.ext.Lists;


@IocBean
public class ShiroUserService {

	@Inject
	private UserService userService ;
	
	@Inject
	private RoleService roleService ;
	
	@Inject
	private PermissionService permissionService ;
	
	
	/**
	 * 查找指定用户id所拥有的角色权限
	 * @param userId
	 * @param userType
	 * @return
	 */
	public List<String> findRolesInfo(Integer userId, Type userType){
		List<Role> roles = roleService.findByUserId(userId, userType);
		List<String> rolesInfo = new ArrayList<String>();
		for (Role role : roles) {
			rolesInfo.add(role.getName());
		}
		return rolesInfo;
	}
	
	
	/**
	 * 查找用户拥有的所有权限信息
	 * @param UserId
	 * @param userType
	 * @return
	 */
	public List<String> findAllPermissionsInfo(Integer userId , Type userType){
		List<Permission> permissions =  findAllPermission(userId, userType);
		List<String> infos = Lists.newArrayList();
		for (Permission perms : permissions) {
			if(perms.isMenu()){
				infos.add(perms.getName());
			}
		}
		return infos;
	}
	
	
	/**
	 * 查找用户拥有的权限
	 * @param userId
	 * @param userType
	 * @return
	 */
	public List<Permission> findAllPermission(Integer userId, Type userType){
		List<Role> roles = roleService.findByUserId(userId, userType);
		List<Permission> permissions = permissionService.findByUser(userId, userType);
		permissions.addAll(permissionService.findByRoles(roles));
		Lists.removeDuplicateWithOrder(permissions);
		Collections.sort(permissions, new Comparator<Permission>(){
			@Override
			public int compare(Permission o1, Permission o2) {
				if(o1.getId() > o2.getId()){  
	                    return 1;  
                }  
                if(o1.getId() == o2.getId()){  
                    return 0;  
                }  
                return -1;  
			}
		});
		return permissions;
	}
}
